<?php
/**
 * Created by PhpStorm.
 * User: krystal
 * Date: 2019/4/22
 * Time: 14:30
 */

namespace app\web\controller;


use app\api\controller\v2\Auth;
use app\common\cachemodel\User;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZlCouponActiveGiveRecord;
use app\common\cachemodel\ZlCouponAttr;
use app\common\lib\Alidayu;
use app\common\lib\exception\ApiException;
use app\common\lib\SensorsData;
use app\common\lib\Util;
use app\common\model\Goods;
use app\common\webmodel\WebSixOneActive2021;
use app\common\webmodel\WebSixOneActiveHistory2021;
use think\Cache;
use think\Controller;
use think\Db;
use think\Env;
use think\Exception;
use think\Log;
use think\response\Json;
use think\Session;
use XznsTools\cache\CacheManage;

class Active extends Controller
{
    public function _initialize()
    {
        parent::_initialize();
        $param = $this->request->param();
        $app_type = $param['app-type'] ?? 'web';
        $version = $param['version'] ?? '';
        $this->assign(['app_type' => $app_type, 'version' => $version]);
        $this->assign('oss', Env::get('host.photo'));
        $this->assign('domain', Env::get('host.domain'));
    }

    /**
     * 2022中秋活动首页
     */
    public function mid_autumn()
    {
        $headers = [
            'app-type' => $this->request->header('app-type'),
            'version' => $this->request->header('version'),
            'did' => $this->request->header('did'),
            'time' => $this->request->header('time'),
            'sign' => $this->request->header('sign'),
            'model' => $this->request->header('model'),
            'phone-version' => $this->request->header('phone-version'),
            'timezone' => $this->request->header('timezone'),
            'distinct-id' => $this->request->header('distinct-id'),
            'access-token' => $this->request->header('access-token'),
        ];
        $type = input('type/s', 'index'); // 页面类型
        $year = input('year/d', 2022); // 2022年的活动
        $h = input('h/d', 0); // 状态栏高度
        $isInApp = 0;

        // 在APP内部访问
        if (in_array($headers['app-type'], ['ios', 'android'], true))
        {
            $isInApp = 1;
        }
        $host = Env::get('host.domain');
        $oss = Env::get('host.photo');

        $data = [];
        switch ($type)
        {
            case 'wish':
                // 许愿页面数据
                $data['wish_list'] = [
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '我希望工作顺利～',
                        'is_self' => 0,
                    ],
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '家人身体健康，事事顺心！事事顺心！事',
                        'is_self' => 1,
                    ],
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '我希望工作顺利～',
                        'is_self' => 0,
                    ],
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '我希望工作顺利～',
                        'is_self' => 0,
                    ],
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '以后暴富～',
                        'is_self' => 0,
                    ],
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '我希望工作顺利～',
                        'is_self' => 0,
                    ],
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '我希望工作顺利～',
                        'is_self' => 0,
                    ],
                    [
                        'avatar' => $oss . '/avatar_default_2.png',
                        'content' => '我希望工作顺利～',
                        'is_self' => 0,
                    ],
                ];
                break;
            case 'lantern':
                // 猜灯谜页面
                $data['card_num'] = 2;
                break;
            case 'exchange':
                // 兑换页面数据
                $data['lantern_num'] = 731; // 已有灯笼数量
                $data['exchange_list'] = [
                    'seven_discount' => [
                        [
                            'id' => 1,
                            'name' => '月运七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 2,
                            'name' => '月度日运七折券',
                            'num' => 38,
                            'status' => 1, // 已兑换
                        ],
                        [
                            'id' => 3,
                            'name' => '合盘报告七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 4,
                            'name' => '年运七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 5,
                            'name' => '恋爱报告七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 6,
                            'name' => '事业报告七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 7,
                            'name' => '财富报告七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 8,
                            'name' => '学业报告七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 9,
                            'name' => '婚姻报告七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 10,
                            'name' => '幸运之城七折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                    ],
                    'eight_discount' => [
                        [
                            'id' => 1,
                            'name' => '月运八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 2,
                            'name' => '月度日运八折券',
                            'num' => 38,
                            'status' => 1, // 已兑换
                        ],
                        [
                            'id' => 3,
                            'name' => '合盘报告八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 4,
                            'name' => '年运八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 5,
                            'name' => '恋爱报告八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 6,
                            'name' => '事业报告八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 7,
                            'name' => '财富报告八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 8,
                            'name' => '学业报告八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 9,
                            'name' => '婚姻报告八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 10,
                            'name' => '幸运之城八折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                    ],
                    'nine_discount' => [
                        [
                            'id' => 1,
                            'name' => '月运九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 2,
                            'name' => '月度日运九折券',
                            'num' => 38,
                            'status' => 1, // 已兑换
                        ],
                        [
                            'id' => 3,
                            'name' => '合盘报告九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 4,
                            'name' => '年运九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 5,
                            'name' => '恋爱报告九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 6,
                            'name' => '事业报告九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 7,
                            'name' => '财富报告九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 8,
                            'name' => '学业报告九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 9,
                            'name' => '婚姻报告九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                        [
                            'id' => 10,
                            'name' => '幸运之城九折券',
                            'num' => 38,
                            'status' => 0,
                        ],
                    ],
                ];
                break;
        }

        return $this->fetch('active/mid_autumn/' . $year . '/' . $type, [
            'header' => json_encode($headers, true),
            'h' => $h, // 导航栏高度
            'is_in_app' => $isInApp,
            'host' => $host,
            'year' => $year,
            'data' => $data,
        ]);
    }

    /**
     * 中秋节相关操作
     */
    public function mid_autumn_operation()
    {
        $operate = input('operate/s', '');
        $code = 200;
        $msg = '操作成功';
        $data = [];
        switch ($operate)
        {
            case 'question_get':
                // 查询剩余灯谜卡是否>=1
//                $code = 0;
//                $msg = '灯谜卡不足';
                // 获取灯谜题目
                $questionList = [
                    [
                        'id' => 1,
                        'title' => '双喜临门（打一地名）',
                        'option_list' => [
                            ['title' => '大理', 'option' => 'A'],
                            ['title' => '重庆', 'option' => 'B'],
                            ['title' => '秦皇岛', 'option' => 'C'],
                        ],
                        'result' => 'B'
                    ],
                    [
                        'id' => 2,
                        'title' => '身教（打一学科）',
                        'option_list' => [
                            ['title' => '英语', 'option' => 'A'],
                            ['title' => '体育', 'option' => 'B'],
                            ['title' => '数学', 'option' => 'C'],
                        ],
                        'result' => 'B'
                    ],
                    [
                        'id' => 3,
                        'title' => '牛多了两条腿（打一字）',
                        'option_list' => [
                            ['title' => '告', 'option' => 'A'],
                            ['title' => '朱', 'option' => 'B'],
                            ['title' => '生', 'option' => 'C'],
                        ],
                        'result' => 'B'
                    ],
                    [
                        'id' => 4,
                        'title' => '全部当掉（打一古代著作）',
                        'option_list' => [
                            ['title' => '史记', 'option' => 'A'],
                            ['title' => '痛典', 'option' => 'B'],
                            ['title' => '春秋', 'option' => 'C'],
                        ],
                        'result' => 'B'
                    ],
                    [
                        'id' => 5,
                        'title' => '一只狗四个口（打一字）',
                        'option_list' => [
                            ['title' => '吼', 'option' => 'A'],
                            ['title' => '思', 'option' => 'B'],
                            ['title' => '器', 'option' => 'C'],
                        ],
                        'result' => 'C'
                    ],
                    [
                        'id' => 6,
                        'title' => '十里空山外，千里雁阵南 （打一节日） ',
                        'option_list' => [
                            ['title' => '中秋节', 'option' => 'A'],
                            ['title' => '端午节', 'option' => 'B'],
                            ['title' => '教师节', 'option' => 'C'],
                        ],
                        'result' => 'A'
                    ],
                ];
                $question = $questionList[array_rand($questionList, 1)];
                $data = [
                    'id' => $question['id'],
                    'title' => $question['title'],
                    'option_list' => $question['option_list'],
                ];
                break;
            case 'question_submit':
                // 提交灯谜答案
                $qid = input('question_id/d', 0);
                $answer = input('answer/s', '');
                if (!$qid || !$answer)
                {
                    $code = 0;
                    $msg = '异常请求';
                } else
                {
                    // 查询答案是否正确 TODO 查询数据库获取答题结果
                    $questionList = [
                        [
                            'id' => 1,
                            'title' => '双喜临门（打一地名）',
                            'option_list' => [
                                ['title' => '大理', 'option' => 'A'],
                                ['title' => '重庆', 'option' => 'B'],
                                ['title' => '秦皇岛', 'option' => 'C'],
                            ],
                            'result' => 'B'
                        ],
                        [
                            'id' => 2,
                            'title' => '身教（打一学科）',
                            'option_list' => [
                                ['title' => '英语', 'option' => 'A'],
                                ['title' => '体育', 'option' => 'B'],
                                ['title' => '数学', 'option' => 'C'],
                            ],
                            'result' => 'B'
                        ],
                        [
                            'id' => 3,
                            'title' => '牛多了两条腿（打一字）',
                            'option_list' => [
                                ['title' => '告', 'option' => 'A'],
                                ['title' => '朱', 'option' => 'B'],
                                ['title' => '生', 'option' => 'C'],
                            ],
                            'result' => 'B'
                        ],
                        [
                            'id' => 4,
                            'title' => '全部当掉（打一古代著作）',
                            'option_list' => [
                                ['title' => '史记', 'option' => 'A'],
                                ['title' => '痛典', 'option' => 'B'],
                                ['title' => '春秋', 'option' => 'C'],
                            ],
                            'result' => 'B'
                        ],
                        [
                            'id' => 5,
                            'title' => '一只狗四个口（打一字）',
                            'option_list' => [
                                ['title' => '吼', 'option' => 'A'],
                                ['title' => '思', 'option' => 'B'],
                                ['title' => '器', 'option' => 'C'],
                            ],
                            'result' => 'C'
                        ],
                        [
                            'id' => 6,
                            'title' => '十里空山外，千里雁阵南 （打一节日） ',
                            'option_list' => [
                                ['title' => '中秋节', 'option' => 'A'],
                                ['title' => '端午节', 'option' => 'B'],
                                ['title' => '教师节', 'option' => 'C'],
                            ],
                            'result' => 'A'
                        ],
                    ];
                    $status = 0;
                    foreach ($questionList as $q)
                    {
                        if ($q['id'] === $qid && $answer === $q['result'])
                        {
                            $status = 1;
                        }
                    }
                    $data = [
                        'status' => $status,
                    ];
                }
                break;
            case 'exchange':
                // 兑换优惠券

                break;
            default:
                $code = 0;
                $msg = '未知操作';
                break;
        }

        return show($code, $msg, $data);
    }

    /**
     * 七夕活动
     */
    public function valentine2022()
    {

        $headers = [
            'app-type' => $this->request->header('app-type'),
            'version' => $this->request->header('version'),
            'did' => $this->request->header('did'),
            'time' => $this->request->header('time'),
            'sign' => $this->request->header('sign'),
            'model' => $this->request->header('model'),
            'phone-version' => $this->request->header('phone-version'),
            'timezone' => $this->request->header('timezone'),
            'distinct-id' => $this->request->header('distinct-id'),
            'access-token' => $this->request->header('access-token'),
        ];

        $h = input('h/d', 0); // 状态栏高度
        $code = input('code/s', ''); // 邀请码
        $type = input('type/d', 0); // 要助力的报告类型
        $isInApp = 0;

        // 在APP内部访问
        if (in_array($headers['app-type'], ['ios', 'android'], true))
        {
            $isInApp = 1;
        }

        return $this->fetch('', [
            'header' => json_encode($headers, true),
            'h' => $h, // 导航栏高度
            'code' => $code,
            'is_in_app' => $isInApp,
            'coupon_type' => $type
        ]);
    }

    /**
     * 六一活动
     * @return mixed
     */
    public function children()
    {
        $img = config('oss-img.LabourDay2019');
        // m站地址host
        $host = Env::get('host.m');

        return $this->fetch('children', ['img' => $img, 'host' => $host]);
    }

    /**
     * 双旦首页
     * @return mixed
     * @throws ApiException
     */
    public function shuangdan2020()
    {
        $isTest = false;
        $headers = $this->request->header();
        if (!$isTest)
        {
            //校验token
            try
            {
                $auth = new Auth();
                $auth->checkRequestAuth();
            }
            catch (Exception $e)
            {
                throw new ApiException('双旦活动错误：权限认证失败,请稍后重试！');
            }
        }
        //todo 不同渠道的分享次数
        $shareTypeInfo = [0, 0, 0, 0, 1, 1, 1, 2];
        return $this->fetch('shuangdan2020', ['shareTitle' => '标题', 'descript' => '描述', 'headers' => json_encode($headers, true), 'share_type_info' => json_encode($shareTypeInfo)]);
    }

    /**
     * 双旦分享页
     * @return mixed
     */
    public function shuangdan_share2020()
    {
        return $this->fetch('', ['shareTitle' => '标题', 'descript' => '描述']);
    }

    /**
     * 优惠券领取记录页
     * @return mixed
     * @throws ApiException
     */
    public function shuangdan_records2020()
    {
        $headers = $this->request->header();
        $isTest = false;
        if (!$isTest)
        {
            //校验token
            try
            {
                $auth = new Auth();
                $auth->checkRequestAuth();
                $uid = $auth->user['id'];
            }
            catch (Exception $e)
            {
                throw new ApiException('双旦活动错误：权限认证失败,请稍后重试！');
            }
        } else
        {
            $uid = 12345465;
        }
        return $this->fetch('', ['headers' => json_encode($headers, true),]);
    }

    /**
     * 微信招新
     */
    public function weixinEnroll()
    {
        $img = config('oss-img.weixinEnroll');
        // m站地址host
        $host = Env::get('host.m');
        return $this->fetch('weixin_enroll', ['img' => $img, 'host' => $host]);
    }

    public function map_update()
    {
        $img = config('oss-img.mapUpdate');
        // m站地址host
        $host = Env::get('host.m');

        return $this->fetch('map_update', ['img' => $img, 'host' => $host]);
    }

    public function eleven2020()
    {
        // m站地址host
        $host = Env::get('host.m');
        $oss = Env::get('host.photo');
        return $this->fetch('eleven2020', ['oss' => $oss, 'host' => $host]);
    }

    /**
     * 2021年五一劳动节活动
     * 开始时间 2021-05-01 00:00:00
     * 结束时间 2021-05-05 23:59:59
     * @throws \Exception
     */
    public function worksday2021()
    {
//        $uid = 12346378;
        try
        {
            $auth = new Auth();
            $auth->checkRequestAuth();
            $uid = $auth->user['id'];
        }
        catch (Exception $e)
        {
            throw new ApiException('错误：认证失败,请稍后重试！');
        }

        // 查询用户今天是否已领取
        $isUserReceiveToday = Cache::get('worksday:' . date('Ymd') . ':' . $uid) !== false ? 1 : 0;

        $getTime = time();
        // 今日未领取，且在活动时间范围内
        if (!$isUserReceiveToday && $this->request->isPost() && $getTime < strtotime('2021-05-06 00:00:00'))
        {
            /**
             * 开始领取优惠券
             *               8折券  7.5折券  7折券  免费券
             * 日       5%    80%    12%     5%    3%
             * 月      30%    80%    15%     4%    1%
             * 年      25%    85%    10%     4.5%  0.5%
             * 合盘报告 10%    85%    10%     4%    1%
             * 一生报告 10%    85%    10%     4.5%  0.5%
             * 幸运之城 10%    85%    10%     4%    1%
             * 校准生辰 10%    85%    10%     4%    1%
             */
            // 优惠券类型随机
            $couponTypeRand = random_int(1, 100);
            if ($couponTypeRand <= 5)
            {
                $goodsName = '日运';
                $couponType = 0;
            } elseif ($couponTypeRand <= 35)
            {
                $goodsName = '月运';
                $couponType = 1;
            } elseif ($couponTypeRand <= 60)
            {
                $goodsName = '年运';
                $couponType = 2;
            } elseif ($couponTypeRand <= 70)
            {
                $goodsName = '合盘报告';
                $couponType = 3;
            } elseif ($couponTypeRand <= 80)
            {
                $goodsName = '一生报告';
                $couponType = 4;
            } elseif ($couponTypeRand <= 90)
            {
                $goodsName = '幸运之城';
                $couponType = 5;
            } else
            {
                $goodsName = '校准生辰';
                $couponType = 6;
            }
            // 优惠券折扣随机
            $couponDiscountRand = random_int(1, 1000);
            switch ($couponType)
            {
                case 0:#日运券
                    if ($couponDiscountRand <= 30)
                    {
                        $couponDiscount = 3;
                    } elseif ($couponDiscountRand <= 80)
                    {
                        $couponDiscount = 2;
                    } elseif ($couponDiscountRand <= 200)
                    {
                        $couponDiscount = 1;
                    } else
                    {
                        $couponDiscount = 0;
                    }
                    break;
                case 1:#月运券
                    if ($couponDiscountRand <= 10)
                    {
                        $couponDiscount = 3;
                    } elseif ($couponDiscountRand <= 50)
                    {
                        $couponDiscount = 2;
                    } elseif ($couponDiscountRand <= 200)
                    {
                        $couponDiscount = 1;
                    } else
                    {
                        $couponDiscount = 0;
                    }
                    break;
                case 2:#年运券
                    if ($couponDiscountRand <= 5)
                    {
                        $couponDiscount = 3;
                    } elseif ($couponDiscountRand <= 50)
                    {
                        $couponDiscount = 2;
                    } elseif ($couponDiscountRand <= 150)
                    {
                        $couponDiscount = 1;
                    } else
                    {
                        $couponDiscount = 0;
                    }
                    break;
                case 3:#合盘报告券
                    if ($couponDiscountRand <= 10)
                    {
                        $couponDiscount = 3;
                    } elseif ($couponDiscountRand <= 60)
                    {
                        $couponDiscount = 2;
                    } elseif ($couponDiscountRand <= 150)
                    {
                        $couponDiscount = 1;
                    } else
                    {
                        $couponDiscount = 0;
                    }
                    break;
                case 4:#一生报告券
                    if ($couponDiscountRand <= 5)
                    {
                        $couponDiscount = 3;
                    } elseif ($couponDiscountRand <= 50)
                    {
                        $couponDiscount = 2;
                    } elseif ($couponDiscountRand <= 150)
                    {
                        $couponDiscount = 1;
                    } else
                    {
                        $couponDiscount = 0;
                    }
                    break;
                case 5:#幸运之城券
                    if ($couponDiscountRand <= 10)
                    {
                        $couponDiscount = 3;
                    } elseif ($couponDiscountRand <= 50)
                    {
                        $couponDiscount = 2;
                    } elseif ($couponDiscountRand <= 150)
                    {
                        $couponDiscount = 1;
                    } else
                    {
                        $couponDiscount = 0;
                    }
                    break;
                default:
                    if ($couponDiscountRand <= 10)
                    {
                        $couponDiscount = 3;
                    } elseif ($couponDiscountRand <= 50)
                    {
                        $couponDiscount = 2;
                    } elseif ($couponDiscountRand <= 150)
                    {
                        $couponDiscount = 1;
                    } else
                    {
                        $couponDiscount = 0;
                    }
                    break;
            }
            // 领取到的优惠券ID
            $couponId = 194 + ($couponType * 4) + $couponDiscount;
            $couponUseRangeId = 185 + ($couponType * 4) + $couponDiscount;
            try
            {
                // 查询优惠券具体属性
                $couponDetail = (new ZlCouponAttr())->field('name,desc,type,gids,ur_id')->where('id', $couponId)->findOrFail();

                $cData = [
                    'uid' => $uid,
                    'c_id' => $couponId,
                    'ur_id' => $couponUseRangeId,
                    'start_time' => $getTime,
                    'end_time' => strtotime('+30 day', $getTime),
                    'give_time' => $getTime,
                    'status' => 0,
                    'price' => 0,
                    'is_give' => 0,
                    'create_time' => $getTime,
                    'update_time' => 0,
                ];

                $userCouponModel = new UserCoupon();
                // 写入用户卡券中心
                $ucId = $userCouponModel->insertGetId($cData);
                // 更新用户卡券中心缓存
                $userCouponModel->listDataAdd($uid, [$ucId => $ucId], 1);
                // 更新当前活动用户今天领取记录
                Cache::set('worksday:' . date('Ymd') . ':' . $uid, 1);

                $couponTypeName = [1 => '折扣', 2 => '立减', 3 => '满减', 4 => '随机', 5 => '免费'];
                $gidsArr = explode(',', $couponDetail['gids']);
                $couponRangeArr = (new Goods())->where('id', 'in', $gidsArr)->column('name');
                // 神策打点 75 获得优惠券 AcquireCoupon
                SensorsData::track($uid, true, 'AcquireCoupon', [
                    'refer_name' => '手动领取',
                    'refer_link' => 'zhunle_api',
                    'coupon_name' => $couponDetail['desc'],
                    'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                    'coupon_type' => $couponTypeName[$couponDetail['type']],
                    'coupon_range' => $couponRangeArr,
                    'acquire_channel' => '五一活动',
                    'is_give' => false,
                    'acquire_scene' => '活动H5',
                ]);
            }
            catch (\Exception $e)
            {
                Log::write('五一活动领取优惠券失败：' . $e->getMessage() . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error');
                return show(0, '领取失败，请稍后重试～');
            }

            $data = [
                'coupon_name' => $couponDetail['desc'],
                'goods_name' => $goodsName,
                'coupon_type' => $couponType,
                'coupon_discount' => $couponDiscount,
            ];

            return show(config('code.success'), '领取成功', $data);
        }

        $headers = $this->request->header();
        $host = Env::get('host.m');
        $oss = Env::get('host.photo');

        return $this->fetch('', [
            'headers' => json_encode($headers, true),
            'oss' => $oss,
            'host' => $host,
            'is_receive' => $isUserReceiveToday
        ]);
    }

    /**
     * 2021-06-10 助力高考活动
     * @throws ApiException
     */
    public function ac20210610()
    {
        if ($this->request->isPost())
        {
            // 请求的操作
            $option = input('option/s', '');

            switch ($option)
            {
                // 领取优惠券
                case 'receive':
                    $data = [

                    ];
                    break;
                // 手机号登录

                // 给ta助力

            }

            return show(config('code.success'), '请求成功', []);
        } elseif ($this->request->header('access_token'))
        {// APP 内请求
            $isTest = false;
            if (!$isTest)
            {
                //校验token
                try
                {
                    $auth = new Auth();
                    $auth->checkRequestAuth();
                    $uid = $auth->user['id'];
                }
                catch (Exception $e)
                {
                    throw new ApiException('高考助力活动错误：权限认证失败,请稍后重试！');
                }
            } else
            {
                $uid = 2;
            }
            $res = (new WebSixOneActive2021())->activeInfo($uid);
        } else
        { // APP 外请求
            $userTel = Session::get('tel');
            $soId = input('soid/d', 0);
            $res = (new WebSixOneActive2021())->field('uid,score,give_num,v1,v2,v3,v4,v5,v6,id')->where('id', $soId)->find();
            if (!$res)
            {
                throw new ApiException('高考助力活动错误：服务异常！');
            }
            $history = (new WebSixOneActiveHistory2021())->where(['tel' => $userTel, 'so_id' => $soId])->find();
            $isAssist = 0;//是否已经助力当前用户
            if ($history)
            {
                $isAssist = 1;
            }
        }

        $history = (new WebSixOneActiveHistory2021())->acriveInfoHistory($res['id']);
        $host = Env::get('host.domain');
        $mhost = Env::get('host.m');
        $oss = Env::get('host.photo');
        $app_type = $this->request->header('app-type', 'web');
        $soId = input('soid/d', 0);
        // 邀请好友助力时，分享的信息，链接需要带上用户信息
        $shareInfo = [
            'title' => '助力梦想，领取你的一生报告',
            'message' => '为好友助力加码，领取好礼！',
            'url' => $host . '/web/active/ac20210610?soid=' . $res['id'],
        ];

        $headers = [
            'app-type' => $this->request->header('app-type'),
            'version' => $this->request->header('version'),
            'did' => $this->request->header('did'),
            'time' => $this->request->header('time'),
            'sign' => $this->request->header('sign'),
            'model' => $this->request->header('model'),
            'phone-version' => $this->request->header('phone-version'),
            'timezone' => $this->request->header('timezone'),
            'distinct-id' => $this->request->header('distinct-id'),
            'access-token' => $this->request->header('access-token'),
        ];

        $data = [
            'my_score' => $res['score'],// 当前累计助力值 超过100重置为100
            'score_list' => [
                [
                    'score' => 10,
                    'is_get_coupon' => $res['v1'],// 是否已领取优惠券
                ],
                [
                    'score' => 30,
                    'is_get_coupon' => $res['v2'],// 是否已领取优惠券
                ],
                [
                    'score' => 50,
                    'is_get_coupon' => $res['v3'],// 是否已领取优惠券
                ],
                [
                    'score' => 70,
                    'is_get_coupon' => $res['v4'],// 是否已领取优惠券
                ],
                [
                    'score' => 90,
                    'is_get_coupon' => $res['v5'],// 是否已领取优惠券
                ],
                [
                    'score' => 100,
                    'is_get_coupon' => $res['v6'],// 是否已领取优惠券
                ],
            ],
            'history_list' => $this->getGiveRecord(),
            'add_list' => $history,
        ];

//        $data = [
//            'my_score' => 70,// 当前累计助力值 超过100重置为100
//            'score_list' => [
//                [
//                    'score' => 10,
//                    'is_get_coupon' => 1,// 是否已领取优惠券
//                ],
//                [
//                    'score' => 30,
//                    'is_get_coupon' => 0,// 是否已领取优惠券
//                ],
//                [
//                    'score' => 50,
//                    'is_get_coupon' => 0,// 是否已领取优惠券
//                ],
//                [
//                    'score' => 70,
//                    'is_get_coupon' => 0,// 是否已领取优惠券
//                ],
//                [
//                    'score' => 90,
//                    'is_get_coupon' => 0,// 是否已领取优惠券
//                ],
//                [
//                    'score' => 100,
//                    'is_get_coupon' => 0,// 是否已领取优惠券
//                ],
//            ],
//            'history_list' => [
//                []
//            ],
//            'add_list' => [
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//                ['avatar' => 'https://oss.goddessxzns.com/active/ac20210610/avatar.png', 'name' => '天高任鸟飞...', 'score' => 8],
//            ],
//        ];

        if (!empty($userTel))
        {
            $isLogin = $userTel ? true : false;
        }
        return $this->fetch('', [
            'isAssist' => $isAssist ?? 0,//助力表识
            'isLogin' => $isLogin ?? false,//登陆表识
            'oss' => $oss,
            'host' => $host,
            'mhost' => $mhost,
            'app_type' => $app_type,
            'so_id' => $soId,
            'share_info' => $shareInfo,
            'headers' => json_encode($headers, true),
            'data' => $data
        ]);
    }

    /**
     * 获取手机验证码
     * @return Json
     * @throws \Exception
     */
    public function getCode()
    {
        $tel = input('param.tel/s', '');
        $areaCode = input('area_code/d', 86);
        $codeGetTime = Cache::get('get_six_code_' . $areaCode . $tel);
        if ($codeGetTime)
        {
            $reTime = $codeGetTime + 60 - time();
            return show(config('code.error'), '请勿频繁发送', $reTime > 0 ? $reTime : 0);
        }
        Cache::set('get_six_code_' . $areaCode . $tel, time(), 60);
        /**
         * 过滤非法获取验证码请求，直接返回发送成功
         */
        if (Util::isIllegalRequest(true))
        {
            return show(config('code.success'), '发送成功');
        }
        $code = random_int(100000, 999999);// 六位验证码
        $alidayu = (new AppConfig())->configInfo('alidayu');
        $smsIdConfigKey = $areaCode === 86 ? 'login_code' : 'abroad_login_code';
        if ($areaCode === 1)
        {
            $result = Alidayu::getInstance()->sendSmsUSA($tel, $code, $smsIdConfigKey);
        } else
        {
            $result = Alidayu::getInstance()->sendSms($tel, $code, $alidayu[$smsIdConfigKey], $areaCode);
        }
        if (!$result)
        {
            return show(config('code.error'), '发送失败');
        }
        return show(config('code.success'), '发送成功');
    }

    /**
     * 高考助力登陆
     * @return Json
     */
    public function acLogin20210610()
    {
        $param = [
            'area' => input('area_code/d', 86),
            'tel' => input('tel/s', ''),
            'code' => input('code/s', '')
        ];
        if (!$param['tel'] || !$param['code'])
        {
            return show(config('code.error'), '请求异常');
        }
        //  validate 严格校验
        $code = Alidayu::getInstance()->checkSmsIdentify($param['tel']);
        if ($code != $param['code'])
        {
            return show(config('code.error'), '短信验证码错误');
        }
        //登陆凭证
        $tel = $param['area'] === 86 ? $param['tel'] : $param['area'] . '-' . $param['tel'];
        Session::set('tel', $tel);
        return show(config('code.success'), '登陆成功');
    }

    /**
     * 高考助力接口
     * @throws \Exception
     */
    public function activeHelp()
    {
        $soId = input('soid/d', 0);

        if (!$soId)
        {
            return show(config('code.error'), '请求异常');
        }

        $userTel = Session::get('tel');

        if (!$userTel)
        {
            return show(403, '登录失效！请重新登录～');
        }

        $info = (new WebSixOneActive2021())->where('id', $soId)->find();

        if ($info)
        {
            if ((new WebSixOneActiveHistory2021())->where(['tel' => $userTel, 'so_id' => $soId])->count())
            {
                return show(config('code.error'), '您已助力过了～');
            }
            if ($info['score'] < 1)
            {   // 首次助力
                $score = 10;
            } elseif ($info['score'] >= 100)
            {
                return show(config('code.error'), '全部助力完成～');
            } else
            {
                $score = random_int(8, 12);
                if ($info['score'] + $score > 100)
                {
                    $score = 100 - $info['score'];
                }
            }
            $resScore = $info['score'] + $score;
            $userInfo = (new User())->where('tel', $userTel)->field('id,avatar,nickname')->find();
            if ($userInfo && $userInfo['id'] == $info['uid'])
            {
                return show(config('code.error'), '自己不能给自己助力');
            }

            // 更新用户助力值
            (new WebSixOneActive2021())->updateData($info['uid'], $soId, ['score' => $resScore]);

            // 写入用户助力记录
            $recodeData = [
                'tel' => $userTel,
                'uid' => $userInfo['id'] ?? 0,
                'so_id' => $soId,
                'score' => $score,
                'create_time' => $this->request->time(),
                'name' => $userInfo['nickname'] ?? '',
                'avatar' => $userInfo['avatar'] ?? '',
            ];
            $recodeId = (new WebSixOneActiveHistory2021())->insertGetId($recodeData);
            // 写入用户助力记录 缓存
            (new WebSixOneActiveHistory2021())->listDataAdd($soId, [$recodeId => $recodeId]);

            return show(config('code.success'), '助力成功', [
                'score' => $score, // 当前助力
                'total_score' => $resScore, // 总助力值
            ]);
        } else
        {
            return show(config('code.error'), '请求异常');
        }
    }

    private function getGiveRecord()
    {
        $redis = CacheManage::getInstance()->redisHandler;

        $giveData = $redis->lRange('active:six_ten:give:info', 0, -1);

        $giveData = $giveData ?: [];

        $i = [
            27 => '一生报告九折券',// 9折
            26 => '一生报告八五折券',// 八五折
            25 => '一生报告八折券',// 八折
            24 => '一生报告七五折券',// 七五折
            23 => '一生报告七折券',// 七折
            22 => '一生报告六折券',// 六折
        ];

        $data = [];
        foreach ($giveData as $value)
        {
            $d = json_decode($value, true);

            // $d['avatar'] = $d['avatar'] ? Env::get('host.photo') . $d['avatar'] : '/static/new_year_activ/img/avatar.png';

            $d['cname'] = $i[$d['id']] ?? '';

            if ($d['cname'])
            {
                $data[] = $d;
            }
        }

        return $data;
    }

    public function fortune_share()
    {
        $h = input('h/d', 0);
        $header = [
            'version' => $this->request->header('version'),
            'time' => $this->request->header('time'),
            'distinct-id' => $this->request->header('distinct-id'),
            'phone-version' => $this->request->header('phone-version'),
            'app-type' => $this->request->header('app-type'),
            'did' => $this->request->header('did'),
            'access-token' => $this->request->header('access-token'),
            'model' => $this->request->header('model'),
            'sign' => $this->request->header('sign'),
        ];


        $date = date('Y-m-d');  //当前日期

        $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期

        $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6

        $now_start = strtotime("$date -" . ($w ? $w - $first : 6) . ' days'); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天

        $now_end = strtotime('+6 days', $now_start);  //本周结束日期

        $last_start = strtotime('-7 days', $now_start);  //上周开始日期

        $last_end = strtotime('-1 days', $now_start);  //上周结束日期

        try
        {
            $fortuneShareConfig = (new AppConfig())->configInfo('fortune_share');
            $prizeName = Cache::get('poster_active:coupon_prize:name', null);
            $fortuneShareConfig['prize1'] = explode(':', $fortuneShareConfig['prize1']);
            $fortuneShareConfig['prize2'] = explode(':', $fortuneShareConfig['prize2']);
            $fortuneShareConfig['prize3'] = explode(':', $fortuneShareConfig['prize3']);
            $fortuneShareConfig['prize4'] = explode(':', $fortuneShareConfig['prize4']);
            if (!$prizeName || !isset($prizeName[$fortuneShareConfig['prize1'][0]], $prizeName[$fortuneShareConfig['prize2'][0]], $prizeName[$fortuneShareConfig['prize3'][0]], $prizeName[$fortuneShareConfig['prize4'][0]]))
            {
                $prizeName = Db::table('wechat_backup_07_18_14_43_00.zl_coupon_attr')->whereIn('id', [$fortuneShareConfig['prize1'][0], $fortuneShareConfig['prize2'][0], $fortuneShareConfig['prize3'][0], $fortuneShareConfig['prize4'][0]])->column('desc', 'id');
            }

            $prizeData = [
                'prize1' => $prizeName[$fortuneShareConfig['prize1'][0]] . ($fortuneShareConfig['prize1'][1] ?? 1) . '张',
                'prize2' => $prizeName[$fortuneShareConfig['prize2'][0]] . ($fortuneShareConfig['prize2'][1] ?? 1) . '张',
                'prize3' => $prizeName[$fortuneShareConfig['prize3'][0]] . ($fortuneShareConfig['prize3'][1] ?? 1) . '张',
                'prize4' => $prizeName[$fortuneShareConfig['prize4'][0]] . ($fortuneShareConfig['prize4'][1] ?? 1) . '张',
            ];
        }
        catch (\Exception $e)
        {
            $prizeData = [
                'prize1' => '',
                'prize2' => '',
                'prize3' => '',
                'prize4' => '',
            ];
            Log::write("海报评选活动 奖品配置错误,{$e->getMessage()},File:{$e->getFile()},Line:{$e->getLine()}", 'error', true);
        }

        return $this->fetch('fortune_share', [
            'h' => $h,
            'header' => json_encode($header),
            'this_week_start' => date('m.d', $now_start),
            'this_week_end' => date('m.d', $now_end),
            'last_week_start' => date('m.d', $last_start),
            'last_week_end' => date('m.d', $last_end),
            'prize_data' => $prizeData
        ]);
    }

    public function iosFeedback()
    {
        $headers = $this->request->header();
        $height = input('h/d', 0);
        //校验token
        try
        {
            $auth = new Auth();
            $auth->checkRequestAuth();
            $uid = $auth->user['id'];
        }
        catch (Exception $e)
        {
            $uid = 0;
        }
        $activId = 28;
        $isGive = false;
        if ($uid)
        {
            $couponActiveGiveRecordModel = new ZlCouponActiveGiveRecord();
            $giveRecordData = $couponActiveGiveRecordModel->getGiveRecord($uid);
            $giveRecordDataIds = empty($giveRecordData) ? [] : array_keys($giveRecordData);
            if (in_array($activId, $giveRecordDataIds))
            {
                $isGive = true;
            }
        }

        return $this->fetch('ios_feedback', [
            'headers' => json_encode($headers),
            'app_type' => $this->request->header('app-type', 'web'),
            'is_login' => 1,
            'height' => $height,
            'is_show_nav' => true,
            'is_give' => $isGive
        ]);
    }

    /**
     * 0元脉轮体验
     * @return mixed
     */
    public function chakrasSample()
    {
        $headers = request()->header();
        $hour = date('G');
        $total = 24;
        if (0 < $hour && $hour < 24)
        {
            $residue = $total - $hour;
        } else
        {
            $residue = 24;
        }
        return $this->fetch('chakras_sample', ['header' => json_encode($headers, true), 'total' => 100, 'residue' => $residue]);
    }

    /**
     * 私人定制手串，点击打开添加企业微信
     */
    public function page2024008()
    {
        $type = input('type/d', 0);
        $appType = $this->request->header('app-type', '');

        switch ($type)
        {
            case 1:
                // 准有好事
                $data = [
                    '/active/web/images/page2024008/0/1.png',
                    '/active/web/images/page2024008/0/2.png',
                    '/active/web/images/page2024008/0/3.png',
                    '/active/web/images/page2024008/0/4.png',
                    '/active/web/images/page2024008/0/5.png',
                    '/active/web/images/page2024008/0/6.png',
                    '/active/web/images/page2024008/0/7.png',
                    '/active/web/images/page2024008/0/8.png',
                    '/active/web/images/page2024008/0/9.png',
                    '/active/web/images/page2024008/0/10.png',
                    '/active/web/images/page2024008/0/11.png',
                    '/active/web/images/page2024008/0/12.png',
                    '/active/web/images/page2024008/0/13.png',
                    '/active/web/images/page2024008/0/14.png',

                    '/active/web/images/page2024008/1/1.png',
                    '/active/web/images/page2024008/1/2.png',
                    '/active/web/images/page2024008/1/3.png',
                    '/active/web/images/page2024008/1/4.png',
                    '/active/web/images/page2024008/1/5.png',
                    '/active/web/images/page2024008/1/6.png',
                    '/active/web/images/page2024008/1/7.png',
                    '/active/web/images/page2024008/1/8.png',
                    '/active/web/images/page2024008/1/9.png',
                    '/active/web/images/page2024008/1/10.png',
                    '/active/web/images/page2024008/1/11.png',
                    '/active/web/images/page2024008/1/12.png',
                    '/active/web/images/page2024008/1/13.png',
                ];
                $link = [
                    'app' => 'jump_mobile_browser?link=https%3A%2F%2Fwork.weixin.qq.com%2Fca%2Fcawcde9b2f9db4bef8&need_auth=0',
                    'h5' => 'https://work.weixin.qq.com/ca/cawcde9b2f9db4bef8',
                ];
                break;
            default:
                // 准了
                $data = [
                    '/active/web/images/page2024008/0/1.png',
                    '/active/web/images/page2024008/0/2.png',
                    '/active/web/images/page2024008/0/3.png',
                    '/active/web/images/page2024008/0/4.png',
                    '/active/web/images/page2024008/0/5.png',
                    '/active/web/images/page2024008/0/6.png',
                    '/active/web/images/page2024008/0/7.png',
                    '/active/web/images/page2024008/0/8.png',
                    '/active/web/images/page2024008/0/9.png',
                    '/active/web/images/page2024008/0/10.png',
                    '/active/web/images/page2024008/0/11.png',
                    '/active/web/images/page2024008/0/12.png',
                    '/active/web/images/page2024008/0/13.png',
                    '/active/web/images/page2024008/0/14.png',

                    '/active/web/images/page2024008/1/1.png',
                    '/active/web/images/page2024008/1/2.png',
                    '/active/web/images/page2024008/1/3.png',
                    '/active/web/images/page2024008/1/4.png',
                    '/active/web/images/page2024008/1/5.png',
                    '/active/web/images/page2024008/1/6.png',
                    '/active/web/images/page2024008/1/7.png',
                    '/active/web/images/page2024008/1/8.png',
                    '/active/web/images/page2024008/1/9.png',
                    '/active/web/images/page2024008/1/10.png',
                    '/active/web/images/page2024008/1/11.png',
                    '/active/web/images/page2024008/1/12.png',
                    '/active/web/images/page2024008/1/13.png',
                ];
                $link = [
                    'app' => 'jump_mobile_browser?link=https%3A%2F%2Fwork.weixin.qq.com%2Fca%2Fcawcdee3012a1aa535&need_auth=0',
                    'h5' => 'https://work.weixin.qq.com/ca/cawcdee3012a1aa535',
                ];
                break;
        }

        $data = [
            '/active/web/images/page2024008/2/1.png',
            '/active/web/images/page2024008/2/2.png',
            '/active/web/images/page2024008/2/3.png',
            '/active/web/images/page2024008/2/4.png',
            '/active/web/images/page2024008/2/5.png',
            '/active/web/images/page2024008/2/6.png',
            '/active/web/images/page2024008/2/7.png',
        ];
        $oss = Env::get('host.photo');
        return $this->fetch('', [
            'images' => $data,
            'oss' => $oss,
            'app_type' => $appType,
            'link' => $link,
        ]);
    }

    /**
     * 私人定制手串，点击打开添加企业微信
     */
    public function page2024009()
    {
        $appType = $this->request->header('app-type', '');
        $link = [
            'app' => 'jump_mobile_browser?link=https%3A%2F%2Fwork.weixin.qq.com%2Fca%2Fcawcdee3012a1aa535&need_auth=0',
            'h5' => 'https://work.weixin.qq.com/ca/cawcdee3012a1aa535',
        ];

        $data = [
            '/active/web/images/page2024009/1.png',
            '/active/web/images/page2024009/2.png',
            '/active/web/images/page2024009/3.png',
            '/active/web/images/page2024009/4.png',
            '/active/web/images/page2024009/5.png',
        ];
        $oss = Env::get('host.photo');
        return $this->fetch('', [
            'images' => $data,
            'oss' => $oss,
            'app_type' => $appType,
            'link' => $link,
        ]);
    }
}
